﻿using DreamWork.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Collections;
using DreamWork.Configuration;
using System.Globalization;

namespace DreamWork.Model
{
    public static partial class ViewModelExtensions
    {
        public static IEnumerable<MetaData> GetMetaData<TEntity>(this TEntity source) where TEntity : ViewModelBase
        {
            return GetMetaData(source);
            IEnumerable<MetaData> GetMetaData<T>(T chidSource)
            {
                var properties = chidSource.GetType().GetProperties();
                return properties.Select(x =>
                {
                    var dataType = x.GetCustomAttributes(false).OfType<DataTypeAttribute>().FirstOrDefault()?.CustomDataType ?? string.Empty;
                    var metaData = new MetaData()
                    {
                        Name = x.Name[0].ToString(CultureInfo.InvariantCulture).ToLower(DreamWorkConstrants.CultureInfo) + x.Name.Substring(1),
                        Label = x.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault()?.DisplayName ?? string.Empty,
                        DataType = x.GetCustomAttributes(false).OfType<DataTypeAttribute>().FirstOrDefault()?.CustomDataType ?? string.Empty,
                        IsKey = x.GetCustomAttributes(false).OfType<DataKeyAttribute>().FirstOrDefault()?.IsDataKey ?? false,
                        IsVisibale = x.GetCustomAttributes(false).OfType<VisibleAttribute>().FirstOrDefault()?.IsVisible ?? true,
                        FieldOrder = x.GetCustomAttributes(false).OfType<FieldOrderAttribute>().FirstOrDefault()?.FieldOrder,

                    };
                    if (dataType == nameof(MetaDataType.SubData))
                    {
                        if (x.PropertyType.IsGenericType
                            && ((x.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                                || x.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
                        {
                            var childType = x.PropertyType.GetGenericArguments().FirstOrDefault();
                            metaData.Children = GetMetaData(Activator.CreateInstance(childType));
                        }
                        else
                        {
                            metaData.Children = GetMetaData(Activator.CreateInstance(x.PropertyType));
                        }
                    }
                    return metaData;
                }
                ).OrderBy(x => x.FieldOrder);
            }
        }
    }
}
